﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;

namespace SharpTrainer.Util
{
    public class JsonSerializer
    {
        public static T Json2ModelJS<T>(string JsonStr)
        {            
            JavaScriptSerializer jss = new JavaScriptSerializer();       
            T userJson = jss.Deserialize<T>(JsonStr); 
            
            return userJson;
        }

        public static string Model2JsonJS<T>(T model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string userJson = jss.Serialize(model);
            
            return userJson;
        }         
        
        public static T Json2Model<T>(string jsonString)
        {            
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {                
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);            
            }        
        }        
        
        public static string Model2Json<T>(T jsonObject)        
        {            
            using (var ms = new MemoryStream())            
            {                
                new DataContractJsonSerializer(typeof(T)).WriteObject(ms, jsonObject);                
                
                return Encoding.UTF8.GetString(ms.ToArray());            
            }        
        }
    }
}
